import router from "@/router";
import axios from "axios";
import store from "@/store";
import { Message } from 'element-ui'
import { getToken } from "@/utils/auth";
const BASEURL = process.env.NODE_ENV === "production" ? "" : "/api";
import { startLoading, endLoading } from './loading'

const service = axios.create({
  baseURL: BASEURL,
  timeout: 50000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (!['/videos/monitorPartners/datasPan', '/videos/monitorPartners/hasUnusual', '/videos/monitorPartners/dayData'].includes(config.url)) {
      startLoading(window.location.hash)
    }

    if (store.getters.token) {
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    if (config.contentType) {
      config.headers["Content-Type"] = config.contentType
    }
    if (config.responseType) {
      config.headers["Response-Type"] = config.responseType
    }
    config.headers["from"] = 'web'
    return config;
  },
  (error) => {
    endLoading()
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    endLoading();
    let url = response.config.url;
    if (url.indexOf("/tollCollectors/exportExcel") != -1 || url.indexOf("/worker/exportWord") != -1) {
      let message = '';
      if (response.headers.message) {
        message = JSON.parse(decodeURIComponent(response.headers.message, "UTF-8"));
      }

      return {
        blob: response.data,
        message
      };
    }
    if (url.indexOf("/file/downLoadFile") != -1) {
      let fileName = JSON.parse(decodeURIComponent(response.headers.filename, "UTF-8"));
      return {
        data: response.data,
        fileName
      };
    }

    const message = response.data.message;
    const code = response.data.code;
    const showMessage = response.config.showMessage;
    if (code !== 10001) {
      Message({
        message: message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (code === 10004) {
        store.dispatch('user/logout').then(() => {
          location.reload();
        })
      }
      return Promise.reject(new Error(message || 'Error'))
      // switch (code) {
      //   case 401:
      //     if (router.currentRoute.name === 'login') {
      //       return Promise.reject(new Error(message))
      //     } else {
      //       this.$message({
      //         message: '您没有权限访问该资源',
      //         type: 'error'
      //       })
      //     }
      //     break
      //   case 10004:  // 登录凭证缺失，需重新登录
      //     this.$message({
      //       message: message,
      //       type: 'error'
      //     })
      //     await this.$store.dispatch('user/logout')
      //     this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      //     break
      //   default:
      //     this.$message({
      //       message: message,
      //       type: 'error'
      //     })
      // }
      // this.$message({
      //   message: message,
      //   type: "error",
      // });
      // store.dispatch('user/resetToken').then(() => {
      //   location.reload()  // 重复登录的情况 
      // })
    } else {
      // 获取数据的接口不需要提示
      // if (message.indexOf("成功") === -1) {
      if ((response.config.method != 'get' && showMessage !== false)) {
        Message({
          message: message,
          type: 'success',
          duration: 2 * 1000
        })
      }
      // }
      return response.data;
    }
  },
  (error) => {
    endLoading()
    if (error.message === "Network Error") {
      Message({
        message: "您的网络开小差了...",
        type: "error",
        duration: 3 * 1000,
      });
    } else if (error.message.includes("timeout")) {
      Message({
        message: "请求超时，请检查网络...",
        type: "error",
        duration: 3 * 1000,
      });
    } else {
      Message({
        message: error.message,
        type: "error",
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);

export default service;
